package com.gitee.wsl.doc.prosemirror.model.attr

import com.gitee.wsl.doc.prosemirror.exception.RangeError

// Attribute descriptors
class Attribute(
    typeName: String,
    attrName: String,
    options: AttributeSpec
) {
    val hasDefault: Boolean = options.hasDefault // Object.prototype.hasOwnProperty.call(options, "default")
    val default: Any? = options.default
    val validate: ((Any?) -> Unit)? = options.validateString?.let { validateType(typeName, attrName, it) }
        ?: options.validateFunction

    val isRequired: Boolean
        get() = !this.hasDefault
}

internal fun validateType(typeName: String, attrName: String, type: String): (Any?) -> Unit {
    val types = type.split("|")
    return { value ->
        val name = value?.let { value::class.simpleName } ?: "null"
        if (types.indexOf(name) < 0) {
            throw RangeError("Expected value of type $types for attribute $attrName on type $typeName, got $name")
        }
    }
}
